﻿
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;

namespace Red.Controls
{
    /// <summary>
    ///     Control displaying checker pattern
    /// </summary>
    public class CheckerRectangle : FrameworkElement
    {
        #region Properties
        
        public static readonly DependencyProperty FirstBrushProperty =
            DependencyProperty.Register( "FirstFill", typeof( Brush ), typeof( CheckerRectangle ),
                new FrameworkPropertyMetadata( new SolidColorBrush( Color.FromRgb( 192, 192, 192 ) ) ) );

        public static readonly DependencyProperty SecondFillProperty =
            DependencyProperty.Register( "SecondFill", typeof( Brush ), typeof( CheckerRectangle ),
                new FrameworkPropertyMetadata( new SolidColorBrush( Color.FromRgb( 96, 96, 96 ) ) ) );

        public static readonly DependencyProperty CheckerFillProperty =
            DependencyProperty.Register( "CheckerSize", typeof( double ), typeof( CheckerRectangle ), new FrameworkPropertyMetadata( 8.0 ) );

        /// <summary>
        ///     Brush for "white" checker fields
        /// </summary>
        public Brush FirstFill
        {
            get { return (Brush)GetValue( FirstBrushProperty ); }
            set { SetValue( FirstBrushProperty, value ); }
        }

        /// <summary>
        ///     Brush for "black" checker fields
        /// </summary>
        public Brush SecondFill
        {
            get { return (Brush)GetValue( SecondFillProperty ); }
            set { SetValue( SecondFillProperty, value ); }
        }

        /// <summary>
        ///     Size of single checker field
        /// </summary>
        public double CheckerSize
        {
            get { return (double)GetValue( CheckerFillProperty ); }
            set { SetValue( CheckerFillProperty, value ); }
        }
        
        #endregion Properties

        #region Event handlers
        
        protected override void OnRender( DrawingContext drawingContext )
        {
            base.OnRender( drawingContext );

            drawingContext.PushClip( new RectangleGeometry( new Rect( 0, 0, ActualWidth, ActualHeight ) ) );

            int xIdx = 0, yIdx;
            for ( double x = 0; x < ActualWidth; x += CheckerSize )
            {
                yIdx = 0;
                for ( double y = 0; y < ActualHeight; y += CheckerSize )
                {
                    bool first = ( xIdx + yIdx ) % 2 == 0;
                    Brush brush = first ? FirstFill : SecondFill;
                    drawingContext.DrawRectangle( brush, null, new Rect( x, y, CheckerSize, CheckerSize ) );
                    ++yIdx;
                }
                ++xIdx;
            }
        }
        
        #endregion Event handlers
    }
}
